import * as vscode from 'vscode';
import * as fs from 'fs';
import { RegexUtils } from './utils/RegexUtils';
import { loadSettings } from './utils/utils';
import * as path from 'path';
import { exec, execSync } from 'child_process';
import * as outputUtils from './utils/OutputUtils';

let outputChannel = outputUtils.OutputUtils.getInstance();

function getAudioDuration(filePath:string):number {
    let settings = loadSettings();
    let ffPath = path.join(path.dirname(settings.rplGenCorePath),"ffprobe.exe");
    let stdout = execSync(`${ffPath} "${filePath}" -show_format -print_format json -hide_banner`);
    let jsonStr = stdout.toString();
    let result = JSON.parse(jsonStr);
    // outputChannel.appendLine("--");
    if(result){
        let duration = Number(result.format.duration);
        return Number(duration.toFixed(3));
    }
    return 0;
}


export async function importLocalSound() {
    let settings = loadSettings();
    let ffPath = path.join(path.dirname(settings.rplGenCorePath), "ffprobe.exe");
    let ffmpegFlag = false;//是否使用ffmpeg填充时间

    const optOnlyPath = "只填充路径";
    const optfillTime = "使用ffmpeg填充时间";

    let selection = await vscode.window.showQuickPick([{
        label: optOnlyPath,
        description: '',
        detail: '只填充路径，不填充时间。语音时间交给回声工坊去填充',
    },
    {
        label: optfillTime,
        description: '需要先配置好回声工坊路径',
        detail: '会使用回声工坊路径下的ffmpeg填充语音时间，暂无进度条，请耐心等待',
    },]);
    if (!selection) {
        return;
    } else {
        switch (selection.label) {
            case optfillTime:
                ffmpegFlag = true;
                if(!fs.existsSync(ffPath)){
                    vscode.window.showErrorMessage(`找不到${ffPath}，请先配置好回声工坊的路径`);
                    return;
                }
                break;
            case optOnlyPath:default:
                ffmpegFlag = false;
                break;
        }
    }

    

    vscode.window.showOpenDialog({ 
        "canSelectFolders": true, 
        "title": "打开存放本地语音文件的文件夹"
    }).then(uris=>{
        //成功
        if(uris) {
            outputChannel.appendLine("开始进行语音导入");
            outputChannel.show();
            let targetPath = uris[0].fsPath;
            //读取文件夹下的文件列表
            let files =  fs.readdirSync(targetPath,{withFileTypes:true});
            files = files.filter(x=>(x.isFile() && /.*\.wav$/.test(x.name)));//获取其中的文件
            // console.log(files);
            if(files.length === 0 ){
                vscode.window.showErrorMessage("该目录下没有wav文件");
                return;
            }

            try {
                let editor = vscode.window.activeTextEditor as vscode.TextEditor;
                if(!editor) {
                    vscode.window.showErrorMessage(`请打开要操作的文件`);
                    return;
                }
                let doc = editor.document;
                let text = doc.getText();
                let lines = text.split("\n");
                let newLines:string[] = [];
                let i = 0;//目前轮到的wav文件

                
                for(let line of lines){
                    if(i >= files.length){
                        //wav文件不够用了
                        // vscode.window.showInformationMessage(`路径“${targetPath}”下的${i}个wav文件不够用`);
                        newLines.push(line);
                        continue;
                    }
                    let dialogLine = RegexUtils.parseDialogueLine(line);
                    if(!dialogLine || !dialogLine.soundEffect.match(/\{\*\}/)){
                        newLines.push(line);//若不是含有待处理星标的对话行，不作处理
                        continue;
                    }

                    //开始导入语音
                    let curFilePath = vscode.Uri.joinPath(vscode.Uri.file(targetPath),files[i++].name).fsPath;
                    let msg = `[${i}/${files.length}=${(i/files.length*100).toFixed(0)}%]'${curFilePath}' -> ${line}`;
                    outputChannel.appendLine(msg);
                    // vscode.window.showInformationMessage(msg);
                    console.log(msg);

                    let duration = ffmpegFlag ? getAudioDuration(curFilePath) : -1;
                    
                    line = line.replace(/\{\*\}/, `{'${curFilePath}';*${duration < 0 ? "" : duration}}`);
                    newLines.push(line);
                    
                }
                outputChannel.appendLine("开始进行替换");
                    
                text = newLines.join("\n");
                
                
                //进行替换
                editor.edit(editorEdit => {
                    let start = new vscode.Position(0,0);
                    let end = start.translate(doc.lineCount,doc.getText().length);
                    let allSelection = new vscode.Range(start,end);
                    editorEdit.replace(allSelection,text); 
                }).then(isSuccess => {
                    if (isSuccess) {
                        
                        vscode.window.showInformationMessage("导入成功！");
                        outputChannel.appendLine("完成语音导入");
                    } else {
                        vscode.window.showErrorMessage("导入失败！");
                    }
                }, err => {
                    vscode.window.showErrorMessage(err);
                });
                //*/
            }catch(error){
                vscode.window.showErrorMessage(""+error);
            }
        }
    },reason=>{
        //失败
        vscode.window.showErrorMessage(`打开文件夹出错，错误原因：${reason}`);
    });
}